package com.skillworld.webapp.model.tutorialservice;

import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.tapestry5.util.TextStreamResponse;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;

import com.skillworld.webapp.model.tutorial.Tutorial;
import com.skillworld.webapp.model.tutorial.Tutorial.Difficulty;


public class TutorialDom 
{
    private String tutorialXml;
    private Document dom;
    
    private String title;
    private String summary;
    private Locale locale;
    private Difficulty difficulty;
    private int duration;
    
    
    public TutorialDom(String tutorialXml)
            throws InvalidTutorialFormat
    {
        this.tutorialXml = tutorialXml;
        parseTutorialcontXml();
    }
    
    
    public String getTitle() 
    {
        return title;
    }

    public String getSummary() 
    {
        return summary;
    }
    
    public Locale getLocale()
    {
        return locale;
    }

    public Difficulty getDifficulty() 
    {
        return difficulty;
    }

    public int getDuration()
    {
        return duration;
    }
    
    
    private static DocumentBuilder getDocumentBuilder()
    {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setIgnoringComments(true);
              dbf.setCoalescing(true);
              dbf.setIgnoringElementContentWhitespace(true);
              dbf.setValidating(false);
              return dbf.newDocumentBuilder();
        } catch (Exception e) 
        { throw new RuntimeException(e); }
    }
      
    private void parseTutorialcontXml()
            throws InvalidTutorialFormat
    {
        try 
        {
            TextStreamResponse t = new TextStreamResponse("text/xml", tutorialXml);
            dom = getDocumentBuilder().parse(new InputSource(t.getStream()));
            
            title = dom.getElementsByTagName("title").item(0).getTextContent();
            summary = dom.getElementsByTagName("abstract").item(0).getTextContent();
            String localeCode = 
                dom.getElementsByTagName("locale").item(0).getTextContent();
            locale = new Locale(localeCode);
            String difficultyAsString = 
                dom.getElementsByTagName("difficulty").item(0).getTextContent();
            difficulty = Difficulty.valueOf(difficultyAsString);
            String durationAsString = 
                dom.getElementsByTagName("duration").item(0).getTextContent();
            duration = Integer.parseInt(durationAsString);
        }
        catch (SAXParseException e)
        { throw new InvalidTutorialFormat(); }
        catch (Exception e) 
        { throw new RuntimeException(e); }
    }
}
